require(['./config'],()=>{
   require(['template','request','header','footer'],(template,request)=>{
      class Goods{
         constructor(){
            this.init()
         }
         init (){
            //从url上取到id。将地址栏的哈希值作为id
            const id = window.location.hash.slice(1)
            //根据id去请求当前分类的数据
            request.getGoods(id).then(resp =>{
               console.log(resp)
               if(resp.code === 200){
                  const list =resp.data.items.list.slice(1)
                  $('#goodsList').prepend(template('goodsTemplate',{list}))
                  $('#price').on('click',()=>{
                     console.log(111)
                     let list =this.sortPrice(resp.data.items.list,'price')
                     $('#goodsList').prepend(template('goodsTemplate',{list}))
                  })
                  $('#letter').on('click',()=>{
                     console.log(222)
                     let list = this.sortTitle(resp.data.items.list, 'saleNum')
                     $('#goodsList').prepend(template('goodsTemplate',{list}))
                  })     
               }
            })
         }
         sortPrice(data,type){
            return data.sort((a,b)=>{
               if(a[type]<b[type]){
                  return 1
               }else if(a[type]>b[type]){
                  return -1
               }else{
                  return 0
               }
            })
         }
         sortTitle (data, type) {
            // [1, 2 ,3 ]
            return data.sort((a, b) => {
                // console.log(a)
                if(a[type]> b[type]){
                    return 1
                } else if(a[type] < b[type]) {
                    return -1
                } else {
                    return 0
                }
            }) 
        }
      }
      new Goods()
   })
})